import React from 'react'
import { Form, Input, Button, message } from 'antd';
import { UserOutlined, LockOutlined } from '@ant-design/icons';
import { useDispatch, useSelector, shallowEqual } from 'react-redux'
import { Redirect } from 'react-router-dom'
import ajax from '../../service/ajax'
import './login.less'

import { createUserAction } from '../../store/actionCreators/login'


import Logo from '../../assets/img/logo.png'


export default function Login(props) {
  const dispatch = useDispatch()
  const { isLogin } = useSelector((state) => ({
    isLogin: state.userInfo.isLogin
  }),shallowEqual)

  const onFinish = async (values) => {

    const { username, password } = values
    let { status, data, msg } = await ajax.post('/login', { username, password })
    if (status === 0) {
      message.success('登录成功')
      dispatch(createUserAction(data))
      // redux改变会重新去渲染login组件，发现redux中的状态已经改变了，就会实现路由的重定向
      // props.history.push('/admin')
    } else {
      message.warning(msg)
    }
  };

  const checkPassword = (rules, value) => {
    if (!value) {
      return Promise.reject('密码不能为空')
    } else if (value.length < 4) {
      return Promise.reject('密码长度必须大于等于4位')
    } else if (value.length > 12) {
      return Promise.reject('密码长度必须小于等于12位')
    }
    return Promise.resolve('密码必须是数字字母下划线')
  }

console.log(isLogin)
  return (
    isLogin ? <Redirect to="/admin" /> : <div id="login">
      <div className="login-header">
        <img src={Logo} alt="" />
        <h1>商品管理系统</h1>
      </div>
      <div className="login-content">
        <h1>用户登录</h1>
        <Form
          name="normal_login"
          className="login-form"
          initialValues={{
            remember: true,
          }}
          onFinish={onFinish}
        >
          <Form.Item
            name="username"
            rules={[
              {
                required: true,
                message: '请输入用户名!',
              }, {
                min: 4,
                message: "用户名长度必须大于等于4位"
              }, {
                max: 12,
                message: "用户名长度必须小于等于12位"
              }
            ]}
          >
            <Input prefix={<UserOutlined className="site-form-item-icon" />} placeholder="用户名" allowClear={true} />
          </Form.Item>
          <Form.Item
            name="password"
            rules={[
              { validator: checkPassword }
            ]}
          >
            <Input
              prefix={<LockOutlined className="site-form-item-icon" />}
              type="password"
              placeholder="密码"
              allowClear={true}
            />
          </Form.Item>

          <Form.Item>
            <Button type="primary" htmlType="submit" className="login-form-button">
              登录
          </Button>
          </Form.Item>
        </Form>
      </div>
    </div>
  )
}
